import axios from 'axios';
import router from '@/router'
import { Message } from 'element-ui';
import { TOKEN_KEY } from '../libs/constant';

const request = axios.create({
    baseURL : process.env.VUE_APP_BASE_API_URL,
    withCredentials : true,
    headers : {
        'content-type': 'application/json',
    }
})

// request 拦截器
request.interceptors.request.use(
    config => {
		config.headers[TOKEN_KEY] = localStorage.getItem(TOKEN_KEY) ? localStorage.getItem(TOKEN_KEY) : '';
        return config;
    },
    error => {
        
        return Promise.reject(error)
    }
)

//response 拦截器
request.interceptors.response.use(
    response => {
        const res = response.data;
		let {code, result} = res;
        if (code === 200) {
            return result
        } else if (code === 301) { //token失效，需要重新登录
            Message({
				message: res.msg,
				type : 'error'
			})
            localStorage.removeItem(TOKEN_KEY);
            router.replace('/login');
			return Promise.reject(res);
        } else {
            Message({
				message: res.msg,
				type : 'error'
			})
			return Promise.reject(res);
        }
    },
    error => {
        Message({
            message: '服务异常，请稍后重试或联系技术人员',
            type : 'error'
        })
        return Promise.reject(new Error('服务异常'));
    }
)

export default request;